package com.vben.file.controller;

import com.vben.common.core.util.R;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class FileDetailController {

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public R<FileInfo> upload(MultipartFile file) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String path = sdf.format(new Date());

        return R.ok(fileStorageService.of(file)
                .setPath(path)
                .upload());
    }

    /**
     * 上传文件，成功返回文件 url
     */
    @PostMapping("/upload/url")
    public R<String> upload2(MultipartFile file) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String path = sdf.format(new Date());

        FileInfo fileInfo = fileStorageService.of(file)
                .setPath(path)
                .upload();
        return R.ok(fileInfo.getUrl());
    }

    /**
     * 上传图片，成功返回文件信息
     * 图片处理使用的是 https://github.com/coobird/thumbnailator
     */
    @PostMapping("/upload-image")
    public FileInfo uploadImage(MultipartFile file) {
        return fileStorageService.of(file)
                .image(img -> img.size(1000, 1000))
                .thumbnail(th -> th.size(200, 200))
                .upload();
    }

    /**
     * 上传文件到指定存储平台，成功返回文件信息
     */
    @PostMapping("/upload-platform")
    public FileInfo uploadPlatform(MultipartFile file) {
        return fileStorageService.of(file)
                .setPlatform("aliyun-oss-1")
                .upload();
    }

    /**
     * 直接读取 HttpServletRequest 中的文件进行上传，成功返回文件信息
     * 使用这种方式有些注意事项，请查看文档 基础功能-上传 章节
     */
    @PostMapping("/upload-request")
    public FileInfo uploadPlatform(HttpServletRequest request) {
        return fileStorageService.of(request).upload();
    }
}